package com.health.viewscontrols.medical.device.bo;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGatt;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.health.tablebean.BTDevice;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.views.BleHeartOxygenConversion;
import com.novabluetooth.views.XueYangHexUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BOKrkActivity extends BaseDeviceActivity {

    private String uuid_service = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";//服务uuid
    private String uuid_characteristic_write = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";//写
    private String uuid_characteristic_notify = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";//读
    private String mBloodOxygen;//血氧值
    private String mHeartRate;//心率值

    @Override
    public void startDevice() {
        checkDeviceMac();
        if (TextUtils.isEmpty(deviceEnum.getMac())) {
            ToastUtils.showShort("请先绑" + deviceEnum.getTitle() + "设备");
            return;
        }
        showProgressDialog("正在搜索" + deviceEnum.getTitle() +  "设备");
        if (!isConnected) {
            blueToothState.setText("蓝牙开始连接");
            if (!TextUtils.isEmpty(deviceEnum.getMac())) {
                mBleDevice.setConnect(true);
                mBleDevice.setMAC(deviceEnum.getMac());
                mBleDevice.connect(deviceEnum.getMac());
            }
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!isConnected) {
                        connectionXueYangBle(deviceEnum.getMac());
                    }
                }
            }, 3200);
        } else {
            ToastUtils.showShort("设备已连接，请等待测量结果");
        }
    }

    private void checkDeviceMac() {
        if (TextUtils.isEmpty(deviceEnum.getMac())) {
            List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
                    "name = '" + deviceEnum.getTitle() + "'");
            if (btDevices != null && btDevices.size() > 0) {
                deviceEnum.setMac(btDevices.get(0).getMacAddress());
            }
        }

        if (TextUtils.isEmpty(deviceEnum.getMac())) {
            ToastUtils.showShort("请先绑" + deviceEnum.getTitle() + "设备");
            return;
        }
    }

    @Override
    public void disconnectDevice() {
        try {
            BleManager.getInstance().disconnectAllDevice();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void bleListener() {
        myBroadcastReceiver.registerReceiver(myBroadcastReceiver);
    }

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.bo_pc_60f);
        BleManager.getInstance().init(getApplication());
        checkDeviceMac();
        bleListener();
    }

    @Override
    public void update(String hexStr) {

    }

    private void initXueYangBle() {

        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setDeviceMac(deviceEnum.getMac())
//                .setDeviceName(true,"PC-60F")
//                .setAutoConnect(true)      // 连接时的autoConnect参数，可选，默认false
//                .setDeviceName(true, "Chipsea-BLE")         // 只扫描指定广播名的设备，可选
                .setScanTimeOut(15000)              // 扫描超时时间，可选，默认10秒；小于等于0表示不限制扫描时间
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);

        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                Log.e(TAG,"*********开始结束**************");
            }

            @Override
            public void onScanStarted(boolean success) {
                Log.e(TAG,"*********开始扫描**************" + success );
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                Log.e(TAG,"*********onScanning**************");
//                connectionXueYangBle(bleDevice);
            }
        });
    }

    private void connectionXueYangBle(final String mac) {
        BleManager.getInstance().connect(mac, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                Log.e(TAG,"*********开始连接**************");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG,"*********连接失败**************");
                blueToothState.setText("蓝牙连接失败");
                isConnected = false;
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                Log.e(TAG,"*********连接成功**************");
                showProgressDialog("等待接收数据");
                isConnected = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if(true){
                            bleWrite(XueYangHexUtils.hexStringToBytes("80"), bleDevice, uuid_service, uuid_characteristic_write);
                            bleNotify(bleDevice, uuid_service, uuid_characteristic_notify);
                        }
                    }
                },200);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                Log.e(TAG,"*********连接中断**************");
                isConnected = false;
                blueToothState.setText("蓝牙已断开");
                cancelProgressDialog();
                setStatusPre();
                BleManager.getInstance().stopNotify(device, uuid_service, uuid_characteristic_notify);
            }
        });
    }

    /**
     * 向蓝牙发送写入数据
     * @param data 写入的byte数据
     */
    @SuppressLint("CheckResult")
    private void bleWrite(final byte[] data, final BleDevice bleDevice, final String uuid_service,
                          String uuid_characteristic_write) {
        BleManager.getInstance().write(
                bleDevice,
                uuid_service,
                uuid_characteristic_write,
                data,
                new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        // 发送数据到设备成功
                        Log.e(TAG, "写入数据成功:" + Arrays.toString(data) );
                    }
                    @Override
                    public void onWriteFailure(BleException exception) {
                        // 发送数据到设备失败
                        Log.e(TAG, "写入数据失败:" + Arrays.toString(data) );
                    }
                });
    }

    /**
     * 订阅接受广播通知
     */
    private void bleNotify(BleDevice bleDevice, String uuid_service, String uuid_characteristic_notify) {
        BleManager.getInstance().notify(
                bleDevice,
                uuid_service,
                uuid_characteristic_notify,
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        // 打开通知操作成功
                    }
                    @Override
                    public void onNotifyFailure(BleException exception) {
                        // 打开通知操作失败
                    }
                    @Override
                    public void onCharacteristicChanged(final byte[] data) {
                        // 打开通知后，设备发过来的数据将在这里出现
//                        Log.e(TAG, "onCharacteristicChanged: " + "收到data==" + Arrays.toString(data)  );
//                        try {
//                            cancelProgressDialog();
//                            cancelTextDialog();
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
                        analysisData(XueYangHexUtils.formatHexString(data, true));
                    }
                });
    }

    //中间数据
    private List<String> tempArrays = new ArrayList<>();

    /**
     * 解析数据
     * @param formatHexString
     */
    private void analysisData(String formatHexString) {
        Log.e(TAG, "analysisData: " + formatHexString );
        String[] strings = formatHexString.split(" ");
        tempArrays.clear();
        if(strings.length < 8){
            return;
        }else if(strings.length > 12){
            for(int i = 0; i< 12 ; i++){
                tempArrays.add(strings[i]);
            }
        }else{
            tempArrays.addAll(Arrays.asList(strings));
        }

        if(BleHeartOxygenConversion.isHeartRateTrue(tempArrays) && BleHeartOxygenConversion.isDataTrue(tempArrays)){
            //检测数据长度是否符合 不符合略过
            mBloodOxygen = Integer.parseInt(tempArrays.get(5), 16)+"";//血氧浓度
            mHeartRate = Integer.parseInt(tempArrays.get(7)+tempArrays.get(6), 16)+"";//脉搏（心率）
            tv_state.setText("实时测量结果");
            tv_result.setText("脉率:" + mHeartRate + "bpm\t\t"+"血氧:" + mBloodOxygen + "%");
            Log.e("showData()3333", "脉率:" + mHeartRate + "bpm\t\t"+"血氧:" + mBloodOxygen + "%");
        }
    }

    private void setStatusPre() {
        tv_state.setText("获取测量结果成功");
        tv_result.setText("脉率:" + mHeartRate + "bpm\t\t"+"血氧:" + mBloodOxygen + "%");
        Log.e(TAG, "setStatusPre: " +  mBloodOxygen + "/" + mHeartRate);
        if (!TextUtils.isEmpty(mBloodOxygen)) {
            DeviceShowSaveData.getDataShow( mBloodOxygen + "/" + mHeartRate, BluetoothConstant.XUEYANG_LIKANG_KRK);
        }
    }

}
